package cn.bjtu.archiprac.papercheck.application.service.impl;

import cn.bjtu.archiprac.papercheck.application.dao.UserDAO;
import cn.bjtu.archiprac.papercheck.application.exception.IncorrectPwdException;
import cn.bjtu.archiprac.papercheck.application.exception.UserExistException;
import cn.bjtu.archiprac.papercheck.application.exception.UserNotFoundException;
import cn.bjtu.archiprac.papercheck.application.model.University;
import cn.bjtu.archiprac.papercheck.application.model.User;
import cn.bjtu.archiprac.papercheck.application.service.iface.IUserService;
import cn.bjtu.archiprac.papercheck.application.vo.UserVO;
import cn.bjtu.archiprac.papercheck.util.Utils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Zexin Lin on 4/12/2018.
 * 用户管理模块接口实现
 */
@Component
public class UserService implements IUserService{
    final private static Logger logger = Logger.getLogger(UserService.class);
    final private UserDAO userDAO;

    @Autowired
    public UserService(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void register(User newUser) throws UserExistException {
        logger.debug("Ready to register: " + newUser);
        UserVO vo = new UserVO();
        vo.setEmail(newUser.getEmail());
        if (userDAO.selectUserByInputParam(vo).size() != 0)
            throw new UserExistException();

        newUser.setUserId(Utils.getUUID());
        newUser.setPassword(Utils.getSHA256Str(newUser.getPassword()));
        userDAO.insertUser(newUser);
    }

    public User login(User user) throws UserNotFoundException, IncorrectPwdException {
        UserVO vo = new UserVO();
        vo.setEmail(user.getEmail());

        List<User> list = userDAO.selectUserByInputParam(vo);
        if (list.size() == 0) {
            throw new UserNotFoundException();
        } else if (list.get(0).getPassword().equals(Utils.getSHA256Str(user.getPassword()))){
            return list.get(0);
        } else {
            throw new IncorrectPwdException();
        }
    }

    public User queryUserInfo(String userId) {
        UserVO queryVO = new UserVO();
        queryVO.setUserId(userId);
        return userDAO.selectUserByInputParam(queryVO).get(0);
    }

    public List<User> queryUserList(UserVO queryMap) {
        return userDAO.selectUserByInputParam(queryMap);
    }

    public void updateUserInfo(User newUser) {

    }

    public void modifyPwd(String userId, String oldPwd, String newPwd) {

    }

    public void applyForCerti(University newUniversity) {

    }
}
